// dojo.provide("apt.PlanningToolBootstrap");
dojo.provide("apt.PlanningTool");
dojo.require("apt.ResourceList");
dojo.require("apt.CalendarComponent");
dojo.require("apt.FilterPopover");
dojo.require("dojo.store.Memory");
dojo.require("dojo.store.JsonRest");
dojo.require("dijit._WidgetBase");
dojo.require("dijit._TemplatedMixin");

dojo.declare("apt.PlanningTool", [dijit._WidgetBase, dijit._TemplatedMixin], {
  templateString: dojo.cache('apt.templates', 'PlanningTool.html'),
  widgetsInTemplate: true,
  // today: new Date(),
  // referenceDate: new Date(),
  // isLogged: '',
  subWidgets: {
    calendarComponentWidget: {},
    resourceWidgets: {},
    dataWidget: {}
  },
  stores: { },
  resizeTimeout: "",
  settings: {},
  daysShowing: 7,
	resources: [],
  filters: [],
  today: '',
	variables: { break: "T", work: "P" },
	dimensions: { sidebarWidth: 180 },

  constructor : function(data){
    this.inherited(arguments);

    //Combine default calendarData with those provided by arguments 
    dojo.safeMixin(this, data);

    this.today = new Date("2012", "5", "11", "12", "00", "00", "00");
    // Generate resources from availability data, becouse we have no other source at this point.
    this.stores.availabilities 	= new dojo.store.JsonRest( { target: "service.svc/114/Calendar" } );
    this.stores.resources 		= new dojo.store.Memory( {data: storedata.resources, idProperty: "SmanId"} );
    this.stores.shifts 			= new dojo.store.Memory({data: storedata.shifts, idProperty: "ShiftId"});
    this.stores.departments 	= new dojo.store.Memory({data: storedata.departments, idProperty: "Code"});
    this.stores.reservations 	= new dojo.store.JsonRest({ target: "service.svc/114/TimeReservations"});
  },
  
  postCreate: function() {
    this._createSubwidgets();

    dojo.connect(window, "onresize", this, "delayedResize");
    document.pt = this;
    
    dojo.connect(this.filterPoint, 'onclick', this, this.toggleFilters);    
    dojo.connect(this.document, "onclick", this, this.clickHandler);
    
    this.resizeSubWidgets();
    
    dojo.query("#ptloading").orphan();
  },
  
  clickHandler: function(event){
    if (dojo.hasClass(event.target, 'reservation') || dojo.hasClass(event.target.parentNode, 'reservation')){
      var target;
      if (dojo.hasClass(event.target, 'reservation')){
        target = event.target;
      } else if ( dojo.hasClass(event.target.parentNode, 'reservation')){
        target = event.target.parentNode;
      }
      
      if (typeof target !== 'undefined'){
        dijit.byNode(target).showInfo();
      }
    }
    if (dojo.hasClass(event.target, 'btn')){
      var parent = event.target.parentNode;
      var target = event.target;
      var value = dojo.attr(target, 'data-pt');
      
      if (dojo.hasClass(target, 'viewbtn') && typeof value != 'undefined' && value > 0){
        dojo.query('.active', parent).removeClass('active');
        dojo.addClass(target, 'active');
        this.changeDaysShowingCustom(value);
      }
      if (dojo.hasClass(target, 'movebtn') && typeof value != 'undefined'){
        this.moveCalendar(value);
      }
    }
  },
  
  moveCalendar: function(value){
    this.subWidgets.calendarComponentWidget.regenerateDays(value);
  },
	
	addResource: function(id){
		var match = false;
		dojo.forEach(this.resources, function(e, i){
			if (e.SmanId == id){
				e.count++;
				match = true;
			}
		});

		if (!match){
			this.resources.push({ SmanId: id, count: 1 });
			this.renderResourceList();
		}
	},
	
	removeResource: function(id){
		var match = false;
		var t = this;
		dojo.forEach(this.resources, function(e, i){
			if ( typeof e !== 'undefined' && e.hasOwnProperty('SmanId') && e.SmanId == id){
				e.count--;
				if (e.count < 1){
					match = i;
				}
			}
		});
		if (match !== false){
			t.resources.splice(match, 1);
			dojo.query('.datarow-' + id).orphan();			
  		t.renderResourceList();					
		}
	},
	  
  toggleFilters: function(e){
    dojo.stopEvent(e);
    if (typeof this.filter !== "object"){
      this.filter = new apt.FilterPopover({parent: this});
    }
    this.filter.show();
    // console.log('toimii');
  },
  
  changeDaysShowingOne: function(event){
    dojo.query('.btn.active').removeClass('active');
    dojo.addClass(event.target, 'active');

    this.changeDaysShowingCustom(1);
  },

  changeDaysShowingWeek: function(event){
    dojo.query('.btn.active').removeClass('active');
    dojo.addClass(event.target, 'active');
    
    this.changeDaysShowingCustom(7);
  },

  changeDaysShowingFive: function(event){
    dojo.query('.btn.active').removeClass('active');
    dojo.addClass(event.target, 'active');
    
    this.changeDaysShowingCustom(5);
  },

  changeDaysShowingCustom: function(days){
    this.daysShowing = days;
    this.resizeSubWidgets();
  },

  delayedResize: function(){
    //Debounce resizing by delaying it for 300ms to save cpu cycles.
    clearTimeout(this.resizeTimeout);
    this.resizeTimeout = setTimeout(dojo.hitch(this, "resizeSubWidgets"), 300);
  },

  _createSubwidgets: function(){
    this.subWidgets.calendarComponentWidget = new apt.CalendarComponent( { startDate: new Date("2012", "5", "11", "12", "00", "00", "00"), parent: this });
    this.subWidgets.calendarComponentWidget.placeAt(this.calendarComponentContainer);
    this.subWidgets.calendarComponentWidget.startup();		
		
		this.resizeSubWidgets();
	},
  
  _showFilters: function() {
  },

  resize: function(){
    this.resizeSubWidgets();
  },

  resizeSubWidgets: function(){
		dojo.style(this.sidebarNode, 'width', this.dimensions.sidebarWidth + "px");
		var contentWidth = dojo.position(this.domNode).w - this.dimensions.sidebarWidth;

		dojo.style(this.calendarComponentContainer, 'width', contentWidth + "px");

    this.subWidgets.calendarComponentWidget.resize();
  },
  
  renderResourceList: function() {
    var name = null;
	
    debugger;
	  this.subWidgets.resourceWidgets = this.subWidgets.resourceWidgets || [];
	  dojo.query('.resourceWidget').orphan();
		
    for (var i=0; i < this.resources.length; i++) {
			if (this.resources[i].count > 0){
				var resourceInfo = this.stores.resources.get(this.resources[i]['SmanId']);
        if (typeof resourceInfo != 'undefined' && resourceInfo.hasOwnProperty('Name') && resourceInfo.Name.length > 0){
          name = resourceInfo['Name'];
        } else { 
          name = this.resources[i]['SmanId'];
        }
	      this.subWidgets.resourceWidgets[i] = new apt.ResourceList({ name: name });
	      this.subWidgets.resourceWidgets[i].placeAt(dojo.byId('resourceList'));				
			}
    };
    this.subWidgets.calendarComponentWidget.resizeCalendarComponentHeight();
  },

});

